package com.yunfeng.supercall.activity;

import java.util.Collection;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.ly.quickdev.library.adapter.ListBaseAdapter.ViewHolder;
import com.ly.quickdev.library.utils.JsonUtils;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.app.AppContext;
import com.yunfeng.supercall.bean.FriendsGroupBean;
import com.yunfeng.supercall.bean.SystemContactsBean;
import com.yunfeng.supercall.httputils.MyAjaxCallBack;

/**
 * 好友分组列表
 * 
 * @author 洋
 * 
 */
public class FriendsGroupListActivity extends
		BaseStickyHeaderListActivity<SystemContactsBean> {

	/** The action when call this activity */
	private String mAction;

	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setTitleBar(R.string.super_friend_group);
		mAction = getIntent().getAction();
		resetList();
		findView(R.id.side_bar).setVisibility(View.GONE);
	}

	@Override
	public View getHeaderView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		TextView tv = (TextView) super.getHeaderView(position, convertView,
				parent);
		tv.setText("");
		return tv;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		if (position == 0) {
			startActivity(new Intent(this, SuperSchoolActivity.class));
		}
		if (position == 1) {
			showAddGroupDialog();
		} else if (position > 1) {
			if (ACTION_CHANGE_GROUP.equals(mAction)) {
				Intent i = new Intent();
				FriendsGroupBean group = (FriendsGroupBean) mList.get(position);
				i.putExtra(KEY_DATA, group.getGroupid());
				setResult(RESULT_OK, i);
				finish();
			} else {
				FriendsGroupBean friendsGroup = (FriendsGroupBean) mList.get(position);
				if (friendsGroup.getImgId() != 0) {
					int img = friendsGroup.getImgId();
					if (img == R.drawable.ic_fans) {
						startActivity(new Intent(this,
								FriendsListByGroupActivity.class).putExtra(
								KEY_DATA, -1));
					} else if (img == R.drawable.ic_follows) {
						startActivity(new Intent(this,
								FriendsListByGroupActivity.class).putExtra(
								KEY_DATA, -2));
					}
				} else {
					startActivity(new Intent(this,
							FriendsListByGroupActivity.class).putExtra(
							KEY_DATA,
							((FriendsGroupBean) mList.get(position)).getGroupid()));
				}

			}
		}
	}

	/**
	 * 显示添加分组的对话框
	 */
	private void showAddGroupDialog() {
		Builder mBuilder = new Builder(getActivity());

		final EditText mEditText = new EditText(this);
		mEditText.setHint(R.string.input_name_of_group);
		mBuilder.setNegativeButton(android.R.string.cancel, null);
		mBuilder.setPositiveButton(android.R.string.ok, new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				String text = mEditText.getText().toString();
				if (TextUtils.isEmpty(text)) {
					return;
				}
				JSONObject json = getBaseParams(getActivity());
				try {
					json.put("i_groupname", text);
					json.put("i_photo", "");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				mHttpClient.post(FUNCTION_ADD_GROUP, json,
						new MyAjaxCallBack() {

							@Override
							public void onReceiveError(String msg,
									String errorCode) {
								// TODO Auto-generated method stub
								showToast(msg);
							}

							@Override
							public void onReceiveData(String data, String msg) {
								// TODO Auto-generated method stub
								showToast(msg);
								try {
									JSONObject json = new JSONObject(data
											.substring(1, data.length() - 1));
									int id = json.getInt("groupid");
									startActivity(new Intent(
											FriendsGroupListActivity.this,
											CreateGroupAddFriendsActivity.class)
											.putExtra(KEY_OTHER_ID, id));
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								resetList();
								loadData();
							}
						});
			}
		});
		mBuilder.setTitle(R.string.add_group);
		mEditText.setPadding(4, 4, 4, 4);
		mBuilder.setView(mEditText);
		mBuilder.show();
	}

	private void resetList() {
		mList.clear();
		mList.addAll((Collection<? extends SystemContactsBean>) SystemContactsBean
				.getGroupSystemContactsList(this));
		if (mAdapter != null) {
			mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void loadData() {
		// TODO Auto-generated method stub
		JSONObject json = getBaseParams(getActivity());
		mHttpClient.post(FUNCTION_GET_USER_GROUP_LIST, json,
				new MyAjaxCallBack() {

					@Override
					public void onReceiveError(String msg, String errorCode) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onReceiveData(String data, String msg) {
						// TODO Auto-generated method stub
						List<FriendsGroupBean> temp = JsonUtils.parseList(data,
								FriendsGroupBean.class);
						resetList();
						// Collections.sort(temp);
						mList.addAll(temp);
						if (!ACTION_CHANGE_GROUP.equals(mAction)) {
							int j = 0;
							for (int i = 1; i < mList.size(); i++) {
								SystemContactsBean friendsGroup = (SystemContactsBean) mList
										.get(i);
								// if (friendsGroup.getUserid() != 0) {
								if ("客户".equals(friendsGroup.getNick_name())) {
									j = i;
									break;
								}
							}
							for (SystemContactsBean f : mList) {
								if (f.getUserid() == 0) {
									f.setSticky("-");
								}
							}
							List<FriendsGroupBean> system = FriendsGroupBean
									.getSystemGroup(FriendsGroupListActivity.this);
							mList.addAll(6, system);
						}
						setListAdapter();
					}
				});
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		if (convertView == null) {
			convertView = getLayoutInflater().inflate(
					R.layout.list_item_friends_group, null);
		}
		final SystemContactsBean contacts = mList.get(position);

		final TextView name = ViewHolder.get(convertView, R.id.tv);
		final ImageView iv = ViewHolder.get(convertView, R.id.iv);
		if (contacts instanceof FriendsGroupBean) {
			name.setText(((FriendsGroupBean) mList.get(position)).getGroupname());
			if (contacts.getImgId() != 0) {
				iv.setImageResource(contacts.getImgId());
			} else {
				AppContext.displayImgWithDefault1(iv, mList.get(position)
						.getPhoto());
			}

		} else {
			name.setText((mList.get(position)).getNick_name());
			iv.setImageResource(contacts.getImgId());
		}
		final TextView count = ViewHolder.get(convertView, R.id.count);
		if (count != null) {
			if (contacts instanceof FriendsGroupBean) {
				String num = ((FriendsGroupBean) contacts).getNum();
				if (TextUtils.isEmpty(num)) {
					count.setVisibility(View.GONE);
				} else {
					count.setVisibility(View.VISIBLE);
				}
				count.setText(getString(R.string.user_count,
						((FriendsGroupBean) contacts).getNumber()));
			}
		}

		return convertView;
	}
}
